package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Permission> permissionList=permissionDao.queryPage(queryString);
        return  new PageResult(permissionList.getTotal(),permissionList.getResult());
    }

    /**
     * 添加权限
     * @param permission
     */
    @Override
    public void addPermission(Permission permission) {
        permissionDao.addPermission(permission);
    }

    /**
     * 通过权限Id从数据库中删除权限
     *
     * @param id
     * @return
     */
    public Result delete(Integer id) {
        //通过权限id从数据库中查询是否有外键关联
        Integer count = permissionDao.findCountById(id);
        if (count > 0) {
            return new Result(false, MessageConstant.DELETE_PERMISSION_FAIL_FRO_KEY);
        }
        permissionDao.delete(id);
        return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
    }

    /**
     * 查询所有权限
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    /**
     * 通过角色id查询权限
     * @param id
     * @return
     */
    @Override
    public List<Integer> findByRoleid(Integer id) {
        return permissionDao.findByRoleid(id);
    }


    /**
     * 用id查询权限信息
     * @param id
     * @return
     */
    @Override
    public Permission findPermissionById(Integer id) {
        return permissionDao.findPermissionById(id);
    }

    /**
     * 修改权限
     * @param permission
     */
    @Override
    public void editPermission(Permission permission) {
        permissionDao.editPremission(permission);
    }

}
